using System;
using System.Reactive;
using JetBrains.Annotations;

using Rsdn.SmartApp;

namespace Rsdn.Janus
{
    [ActivePart]
    public class SyncRefreshActivePart : ActivePartBase
    {
        private readonly ISynchronizer _synchronizer;
        private readonly IEventBroker _eventBroker;
        private IDisposable _endSyncSubscription;

        public SyncRefreshActivePart([NotNull] IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            _synchronizer = ServiceProvider.GetRequiredService<ISynchronizer>();
            _eventBroker = ServiceProvider.GetRequiredService<IEventBroker>();
        }

        protected override void ActivateCore()
        {
            Action<EndSyncEventArgs> action = OnAction;
            IObserver<EndSyncEventArgs> observer = Observer.Create<EndSyncEventArgs>(action);
            _endSyncSubscription = _synchronizer.EndSync.Subscribe(observer);
        }

        private void OnAction(EndSyncEventArgs arg)
        {
            if (arg.Result != SyncResult.Finished || arg.StatisticsContainer.IsEmpty())
            {
                return;
            }

            const ForumEntryChangeType FORUM_ENTRY_CHANGE_TYPE =
                ForumEntryChangeType.Synchronized;

            ForumEntryIds[] forumEntryIdses = new[] {ForumEntryIds.AllForums};

            ForumEntryChangedEventArgs forumEntryChangedEventArgs = new ForumEntryChangedEventArgs(forumEntryIdses, FORUM_ENTRY_CHANGE_TYPE);

            _eventBroker.Fire(ForumEventNames.BeforeForumEntryChanged, forumEntryChangedEventArgs);

            ServiceProvider.GetRequiredService<IUIShell>().RefreshData(ServiceProvider);

            _eventBroker.Fire(ForumEventNames.AfterForumEntryChanged, forumEntryChangedEventArgs);
        }

        protected override void PassivateCore()
        {
            _endSyncSubscription.Dispose();
        }
    }
}